package com.apis.javacommon.base;

import com.apis.javacommon.page.Page;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author 
 */
@Transactional
public abstract class BaseManager <E extends BaseEntity,Q extends BaseQuery>{
	public static final Integer DEFAULT_PAGE=1;
	public static final Integer DEFAULT_ROWS=10;
	protected Log log = LogFactory.getLog(getClass());

	protected abstract BaseMapper<E,Q> getBaseMapper();
	
	@Transactional(readOnly=true)
	public E getById(Integer id) throws DataAccessException {
		return (E)getBaseMapper().getById(id);
	}
	
	@Transactional(readOnly=true)
	public List<E> findAll() throws DataAccessException {
		return getBaseMapper().findPage(null);
	}
	
	@Transactional(readOnly=true)
	public List<E> findAllByQuery(Q e) throws DataAccessException {
		return getBaseMapper().findPage(e);
	}
	
	
	
	/** 插入数据 */
	public E save(E entity) throws DataAccessException {
		getBaseMapper().insert(entity);
		return entity;
	}
	@Transactional(readOnly=true)
	public Page findPage(Q query){
		Number totalCount = findPageCount(query);
		query.setPage(query.getPage()==null?DEFAULT_PAGE:query.getPage());
		query.setRows(query.getRows()==null?DEFAULT_ROWS:query.getRows());
		query.setPage(query.getPage()-1);
		Page<E> page = new Page<E>(query.getPage(), query.getRows(), totalCount.intValue());
		if(totalCount.intValue()>0){
			page.setResult(getBaseMapper().findPage(query));
		}
		return page;
	}
	
	private Number findPageCount(Q query){
		return getBaseMapper().findPagecount(query);
	}
	public void physicsDelete(Integer id) throws DataAccessException {
		getBaseMapper().physicsDelete(id);
	}
	public void logicDelete(Integer id) throws DataAccessException {
		getBaseMapper().logicDelete(id);
	}
	public E update(E entity) throws DataAccessException {
		getBaseMapper().update(entity);
		return entity;
	}



}
